Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Middleware Implementation #35

Open
wants to merge 5 commits into
base: dev
Choose a base branch
from

Conversation

shankarThiyagaraajan
Copy link
Contributor

Simple Middleware process were implemented,

ex.
Simple Implementation of Middleware in Route.

$router->post([
    'as' => 'Test',
    'uri' => '/test',
    'middleware' => __NAMESPACE__ . '\Middlewares\Auth',
    'uses' => __NAMESPACE__ . '\Controllers\Test\TestController@test'
]);

Adding additional index for "Middleware" [Route.php],

$this->middleware = $data['middleware'];

Re-Process the Request with Middleware [Router.php],

 protected function processRequest(Route $route)
    {
        // Middleware Implementations
        $route = (new Middleware())->init($route);

        $this->processResponse($route->handle());

    }

New Middleware Module in "Herbert/Framework/Middleware.php",

Creating Folder for Middleware in inside "Plugin/app/Middleware"

Finally Create Custom Middleware to Implement...!

Sample User Rights Handling Middleware :

<?php
namespace Plugin\Middlewares;

use Plugin\Helper;
use Exception;

/**
 * Class Middleware
 * @package Plugin\library
 */
class Auth
{
    /**
     * @var
     */
    protected $request;

    /**
     * @var string
     */
    protected $role = 'administrator';

    /**
     * Auth constructor.
     */
    public function __construct()
    {
        //
    }

    /**
     * Managing Requests
     */
    public function handle($request)
    {
        $user_rights = $this->getUserRights();
        try {
            if (in_array($this->rights, $user_rights)) {
                return $request;
            } else {
                wp_die(__('You do not have sufficient permissions to access this page.'), 403);
            }
        } catch (Exception $e) {
            wp_die(__($e->getMessage()), 403);;
        }
    }


    /**
     * @return mixed
     */
    public function getUserRights()
    {
        return wp_get_current_user()->roles;
    }

}

Route Define ex. 

$router->get([
    'as' => 'URI',
    'uri' => '/name',
    'middleware' => '[your_middlewares]',
    'uses' => __NAMESPACE__ . '\Controllers\Controller_name@function
]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant